import Axios, { AxiosInstance } from 'axios'
import { getToken } from './auth'

const { VITE_BASE_URL } = import.meta.env;

const service: AxiosInstance = Axios.create({
  baseURL: VITE_BASE_URL as string,
  timeout: 60000
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    config.headers.code = getToken();
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code === 405) {
        localStorage.setItem('chatbotToken', '');
        setTimeout(() => {
          location.href = '/login';
        }, 500);
      }
      const msg = res.message || res.msg || '未知错误';
      (window as any).$message.error(msg);
      return Promise.reject(msg)
    }
    return res
  },
  (error) => {
    console.log(error) // for debug
    const msg = error.message || error.msg || '未知错误';
    (window as any).$message.error(msg);
    return Promise.reject(error)
  }
)

export default service
